package com.rjwh.dingdong.client.activity.webbrowser;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.webkit.JavascriptInterface;

import com.aishua.lib.utils.AsStrUtils;
import com.rjwh.dingdong.client.R;
import com.rjwh.dingdong.client.activity.BaseActivity;
import com.rjwh.dingdong.client.application.MyApplication;
import com.rjwh.dingdong.client.service.HttpWebCoreService;
import com.rjwh.dingdong.client.util.AppUtil;
import com.rjwh.dingdong.client.util.FileUtils;
import com.rjwh.dingdong.client.util.GameSoundPaly;
import com.rjwh.dingdong.client.util.LogUtil;
import com.rjwh.dingdong.client.view.X5WebView;
import com.tencent.smtt.sdk.WebSettings;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;

import java.io.File;

import butterknife.BindView;
import butterknife.ButterKnife;


/**
 * 延伸游戏
 *
 * @author 王小珂
 * @ClassName OaGameActivity
 * @Description TODO(这里用一句话描述这个类的作用)
 * @date 2016-1-4 下午3:51:57
 * @history 1.YYYY-MM-DD author: description:
 */
public class OaGameActivity extends BaseActivity {

    @BindView(R.id.game_layout_webview)
    X5WebView webView;
    private String url;
    private View decorView;

    public static void startActivity(Context context, String url) {
        Intent intent = new Intent(context, OaGameActivity.class);
        intent.putExtra("url", url);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //去掉虚拟按键全屏显示
        decorView = getWindow().getDecorView();
        hideNavigation();
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        setContentView(R.layout.game_layout);
        ButterKnife.bind(this);
        parseIntent();
        startWebService();
        setWebView();
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if (hasFocus) {
            hideNavigation();
        }
    }

    //隐藏底部虚拟键
    @TargetApi(Build.VERSION_CODES.KITKAT)
    private void hideNavigation() {
        decorView.setSystemUiVisibility(
                View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                        | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                        | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                        | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                        | View.SYSTEM_UI_FLAG_FULLSCREEN
                        | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
    }

    private void parseIntent() {
        Intent intent = getIntent();
        if (intent != null) {
            url = intent.getStringExtra("url");
        }
    }

    public void startWebService() {

        if(!AppUtil.isServiceRunning(this, MyApplication.getInstance().packgeName+".service.HttpWebCoreService")){
//            LogUtil.e("OaGameActivity", "com.rjwh.dingdong.client.service.HttpWebCoreService");
            startService(new Intent(this, HttpWebCoreService.class));
        }

    }

    @SuppressLint("SetJavaScriptEnabled")
    public void setWebView() {
        WebSettings settings = webView.getSettings();

        settings.setJavaScriptEnabled(true);
        settings.setSupportZoom(false);
        settings.setBuiltInZoomControls(false);
        settings.setDisplayZoomControls(false);

        webView.addJavascriptInterface(new MyJavascriptInterface(), "app");
        if (!AsStrUtils.isEmpty(url)) {
            LogUtil.d("HTME", url);
            webView.loadUrl(url);
        }
        webView.setWebViewClient(new WebViewClient() {

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                LogUtil.d("HTML", "url:" + url);
                view.loadUrl(url);
                return true;
            }

            @Override
            public void onReceivedError(WebView webView, int i, String s, String s1) {
                super.onReceivedError(webView, i, s, s1);
                LogUtil.e("OaGameActivity", " onReceivedError");
//                startWebService();
//                webView.reload();
            }
        });
    }

//    /**
//     * @param uri
//     */
//    public void webBack(Uri uri) {
//        String back = uri.getQueryParameter("back");
//        //back=1,表示直接退回到原生客户端页面；back=0表示回退到网页的上一层
//        if (back.equals("1")) {
//            finish();
//        } else {
//            if (webView.canGoBack()) {
//                webView.goBack();
//            } else {
//                finish();
//            }
//        }
//    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
//            webView.loadUrl("javascript:game.back()", null);
            //如果是在地图界面就直接退出到app
            if (webView.getUrl().contains("map")) {
                finish();
            } else {
                //不在地图就判断
                if (webView.canGoBack()) {
                    webView.goBack();
                } else {
                    finish();
                }
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }


    @Override
    protected void onPause() {
        super.onPause();
        if (webView != null) {
            webView.onPause();
            GameSoundPaly.getInstance().pauseAll();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (webView != null) {
            webView.onResume();
            GameSoundPaly.getInstance().resumeAll();
        }
    }

    @Override
    protected void onDestroy() {
        if (webView != null) {
            webView.setVisibility(View.GONE);
            webView.removeAllViews();
            webView.destroy();
            GameSoundPaly.getInstance().onDestroy();
        }
        super.onDestroy();
    }

    private class MyJavascriptInterface {

        public MyJavascriptInterface() {
        }

        @JavascriptInterface
        public void test(String string) {

            LogUtil.e("MyJavascriptInterface", "string: " + string);
        }

        @JavascriptInterface
        public void back(final int type) {
            webView.post(new Runnable() {
                @Override
                public void run() {

                    LogUtil.e("MyJavascriptInterface", "back");
                    if (type == 0) {
                        LogUtil.e("MyJavascriptInterface", "backtype = " + type);
                        if (webView.canGoBack()) {
                            webView.goBack();
                        } else {
                            OaGameActivity.this.finish();
                        }
                    } else if (type == 1) {
                        LogUtil.e("MyJavascriptInterface", "backtype = " + type);
                        OaGameActivity.this.finish();
                    }


                }
            });

        }


        @JavascriptInterface
        public void play(final String type, final String _path, final String _name, final int _loop, final int role) {
            webView.post(new Runnable() {
                @Override
                public void run() {
                    if (!AppUtil.isForeground(OaGameActivity.this, OaGameActivity.class.getName())) {
                        return;
                    }
                    LogUtil.e("MyJavascriptInterface", "play");
                    File file;
                    //绘本
                    if (type.equals("picture")) {
                        file = new File(FileUtils.getDrwabookDirDirectory(), _path + _name);
                    } else {
                        file = new File(FileUtils.getGameDirectory(), _path + _name);
                    }
                    LogUtil.e("HTML", "soundPath : " + file.getPath());

                    if (file != null && file.exists()) {
                        String path = file.getAbsolutePath();
                        boolean isLoop = _loop == 1;
                        LogUtil.e("HTML", "isLoop : " + isLoop);
                        GameSoundPaly.getInstance().play(role + "", path, isLoop);
                    }
                }
            });

        }

        @JavascriptInterface
        public void stop(final int role) {
            LogUtil.e("MyJavascriptInterface", "stop");
            webView.post(new Runnable() {
                @Override
                public void run() {
                    GameSoundPaly.getInstance().stop(role + "");
                }
            });
        }

        @JavascriptInterface
        public void pause(final int role) {
            LogUtil.e("MyJavascriptInterface", "pause");
            webView.post(new Runnable() {
                @Override
                public void run() {
                    GameSoundPaly.getInstance().pause(role + "");
                }
            });
        }

        @JavascriptInterface
        public void resume(final int role) {
            LogUtil.e("MyJavascriptInterface", "resume");
            webView.post(new Runnable() {
                @Override
                public void run() {
                    GameSoundPaly.getInstance().resume(role + "");
                }
            });

        }
    }
}
